package cn.liontalk.task;

import cn.liontalk.constant.Constant;
import cn.liontalk.dao.BrokerMessageDao;
import cn.liontalk.entity.BrokerMessageLog;
import cn.liontalk.entity.Order;
import cn.liontalk.producer.RabbitmqOrderSender;
import cn.liontalk.utils.FastJsonConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.Date;
import java.util.List;

/**
 * @author ZhouZhe
 * @version 1.0
 * @description
 * @date 2018-12-11 21:28
 **/
@Configuration
public class RetryMessageTasker {


    @Autowired
    private RabbitmqOrderSender rabbitOrderSender;

    @Autowired
    private BrokerMessageDao brokerMessageDao;

    @Scheduled(initialDelay = 5000, fixedDelay = 10000)
    public void reSend() {
        System.out.println("-----------定时任务开始-----------");
        //pull status = 0 and timeout message
        List<BrokerMessageLog> list = brokerMessageDao.queryStatusAndTimeoutMessage();
        list.forEach(messageLog -> {
            if (messageLog.getTryCount() >= 3) {
                //update fail message
                brokerMessageDao.changeBrokerMessageLogStatus(messageLog.getMessageId(), Constant.SEND_FAIL, new Date());
            } else {
                // resend
                brokerMessageDao.updateReSend(messageLog.getMessageId(), new Date());
                System.out.println("===================== ReSend  ==========================");
                Order reSendOrder = FastJsonConvertUtil.convertJSONToObject(messageLog.getMessage(), Order.class);
                try {
                    rabbitOrderSender.sendOrder(reSendOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("-----------异常处理-----------");
                }
            }
        });
    }


}